import { PageContainer } from '@ant-design/pro-layout';
import { Tabs } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useEffect } from 'react';
import SearchBox from '@/components/Search/SearchBox';
import Graphin, { Utils, Behaviors, GraphinContext } from '@antv/graphin';
import { getCreditRisk } from '../../services/credit-risk';
import {
  getAssociateEvent,
  getAssociatePath,
  getAssociateEntity,
} from '../../services/zhirong/associate';
import iconLoader from '@antv/graphin-icons';

const { fontFamily } = iconLoader();
const icons = Graphin.registerFontFamily(iconLoader);

const { TabPane } = Tabs;

const { FitView, DragCanvas, ResizeCanvas } = Behaviors;

const layout = {
  type: 'graphin-force',
  minNodeSpacing: '1',
};

const FocusItem = () => {
  const { graph } = React.useContext(GraphinContext);
  useEffect(() => {
    graph.focusItem('node-0', true);
    graph.setItemState('node-0', 'selected', true);
  }, []);
  return null;
};
const shouldBegin = () => {
  return true;
};

const CreditRisk = () => {
  const [enterprise, setEnterprise] = useState({
    eid: '',
    name: '',
    status: '',
    network: {
      nodes: [],
      edges: [],
    },
  });
  const [data_stock, setDataStock] = useState({});
  const [data_self, setDataSelf] = useState({});
  const [data_corelate, setDataCorelate] = useState({});
  const [activeKey, setActiveKey] = useState(1);
  const [params, setParams] = useState({});

  const dataProcess = (data, enterpriseId) => {
    const { nodes, links } = data;
    nodes.forEach((node) => {
      node.style = {
        icon: {
          fontFamily,
          type: 'font',
          value: node.category === 'E' ? icons.company : icons.user,
          fill: node.id === enterpriseId ? 'red' : '#1890ff',
          size: 25,
          fillOpacity: 0.8,
          // value: icons.home
        },
        keyshape: {
          size: node.id === enterpriseId ? 45 : 40,
          fill: node.id === enterpriseId ? 'red' : '#1890ff',
          stroke: node.id === enterpriseId ? 'red' : '#1890ff',
          fillOpacity: 0.2,
        },
        label: {
          value: node.name,
        },
      };
      node.label = node.name;
    });
    links.forEach((edge) => {
      edge.style = {
        keyshape: {
          fill: '#999',
          stroke: '#999',
          lineWidth: 1,
        },
        label: {
          value: `持股${edge.value * 100}%`,
          fill: '#f00',
        },
      };
    });
    return { nodes, edges: links }; // setNetwork在这里可能是异步执行的？
    // console.log("dataProcess network: ", network) //更改之后的network并不能在这里log出来，所以这里log的结果还是[]
  };

  const getAsyncAssociateEvent = async (params) => {
    const res = await getAssociateEvent(params);
    const { data } = res;
    if (!data) {
      return;
    }
    setDataStock(dataProcess(data.eventList[0], params.centerID));
  };

  const getAsyncAssociateEntity = async (params) => {
    const res = await getAssociateEntity(params);
    const { data } = res;
    if (!data) {
      return;
    }
    setDataSelf(dataProcess(data, params.centerID));
  };

  const getAsyncAssociatePath = async (params) => {
    const res = await getAssociatePath(params);
    const { data } = res;
    if (!data) {
      return;
    }
    setDataCorelate(dataProcess(data, params.centerID));
  };

  const getAsyncSelectValue = (params) => {
    if (activeKey == 1) {
      getAsyncAssociateEvent(params);
    } else if (activeKey == 2) {
      getAsyncAssociateEntity(params);
    } else if (activeKey == 3) {
      getAsyncAssociatePath(params);
    }
  };

  const handleSubmit = async (value) => {
    setEnterprise(value);
    const params = {
      centerID: value.eid,
      dateFrom: '2018-01-01',
      dateTo: '2018-12-31',
      query: true,
    };
    setParams(params);
    getAsyncSelectValue(params);
  };

  useEffect(() => {
    if (Object.keys(params).length === 0) {
      return;
    }
    getAsyncSelectValue(params);
  }, [activeKey]);

  const getAsyncCreditRisk = async () => {
    const res = await getCreditRisk();
    const { data_corelate, data_self, data_stock } = res.data;
    setDataStock(data_stock);
    setDataSelf(data_self);
    setDataCorelate(data_corelate);
  };

  useEffect(() => {
    getAsyncCreditRisk();
  }, []);

  return (
    <PageContainer content={<SearchBox onSubmit={handleSubmit} />}>
      <ProCard split="vertical">
        <ProCard title="" colSpan="25%" cover={<img alt="" src="" />}></ProCard>
        <ProCard title="enterprise" headerBordered>
          <div style={{ height: 200 }}>信息</div>
        </ProCard>
      </ProCard>
      <Tabs
        defaultActiveKey="1"
        onChange={(key) => {
          setActiveKey(key);
        }}
      >
        <TabPane tab="股权风险" key="1">
          <ProCard split="vertical" title="股权风险">
            <ProCard
              title="高股权风险"
              bordered
              headerBordered
              direction="column"
              colSpan="25%"
              gutter={[0, 16]}
              style={{ marginTop: 8 }}
            >
              <ProCard title="环路1" type="inner" bordered>
                a-b-c-a
              </ProCard>
              <ProCard title="环路2" type="inner" bordered>
                a-b-c-a
              </ProCard>
            </ProCard>

            <ProCard title="" headerBordered>
              {Object.keys(data_stock).length > 0 ? (
                <Graphin data={data_stock} layout={layout}>
                  <FitView />
                  <FocusItem />
                  <DragCanvas shouldBegin={shouldBegin} />
                  <ResizeCanvas />
                </Graphin>
              ) : (
                ''
              )}
            </ProCard>
          </ProCard>
        </TabPane>
        <TabPane tab="自身风险" key="2">
          <ProCard split="vertical">
            <ProCard
              title="中自身风险"
              bordered
              headerBordered
              direction="column"
              colSpan="25%"
              gutter={[0, 16]}
              style={{ marginTop: 8 }}
            >
              <ProCard title="民事诉讼" type="inner" bordered>
                共1条记录
              </ProCard>
              <ProCard title="行政处罚" type="inner" bordered>
                无
              </ProCard>
            </ProCard>

            <ProCard>
              {Object.keys(data_self).length > 0 ? (
                <Graphin data={data_self} layout={layout}>
                  <FitView />
                  <ResizeCanvas />
                </Graphin>
              ) : (
                ''
              )}
            </ProCard>
          </ProCard>
        </TabPane>
        <TabPane tab="关联风险" key="3">
          <ProCard split="vertical">
            <ProCard
              title="低关联风险"
              bordered
              headerBordered
              direction="column"
              colSpan="25%"
              gutter={[0, 16]}
              style={{ marginTop: 8 }}
            >
              <ProCard title="" type="inner" bordered>
                共0条记录
              </ProCard>
            </ProCard>
            <ProCard>
              {Object.keys(data_corelate).length > 0 ? (
                <Graphin data={data_corelate} layout={layout}>
                  <ResizeCanvas />
                </Graphin>
              ) : (
                ''
              )}
            </ProCard>
          </ProCard>
        </TabPane>
      </Tabs>
    </PageContainer>
  );
};

export default CreditRisk;
